package com.ybkj.daijia.server.controller;

import com.ybkj.daijia.common.Principal;
import com.ybkj.daijia.server.exception.NoPermissionException;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.partner.Intent;
import com.ybkj.daijia.server.partner.Partner;
import com.ybkj.daijia.server.partner.PartnerImg;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.IntentService;
import com.ybkj.daijia.server.service.PartnerService;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(value = "partner")
public class PartnerController {

    @Autowired
    private PartnerService partnerService;

    @Autowired
    private IntentService intentService;

    @Autowired
    private CompanyService companyService;

    @RequestMapping(value = "list/{categoryAlias}", method = RequestMethod.GET)
    public ModelAndView list(
        @PathVariable("categoryAlias") String categoryAlias,
        @RequestParam(required = false, value = "intentId") Long intentId,
        @RequestParam(required = false, value = "param") String param,
        @RequestParam(required = false, value = "startTime") String startTime,
        @RequestParam(required = false, value = "endTime") String endTime) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("partner")) {
            Date start = null;
            Date end = null;
            try {
                if (StringUtils.isNotBlank(startTime)) {
                    start = DateUtils.parseDate(startTime, "yyyy-MM-dd");
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
            try {
                if (StringUtils.isNotBlank(endTime)) {
                    end = DateUtils.parseDate(endTime, "yyyy-MM-dd");
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
            Page<Partner> page = partnerService
                .findByParam(categoryAlias, intentId, param, start, end);
            ModelAndView mv = new ModelAndView();
            if ("weihu".equals(categoryAlias)) {
                List<Intent> list = intentService.findByCategoryAlias(categoryAlias);
                mv.addObject("intents", list);
            }
            if (subject.isPermitted("intentUpdate") || subject.isPermitted("intentDelete")) {
                mv.addObject("show", "show");
            }
            mv.addObject("page", page);
            mv.addObject("param", param);
            mv.addObject("categoryAlias", categoryAlias);
            mv.addObject("intentId", intentId);
            mv.addObject("startTime", startTime);
            mv.addObject("endTime", endTime);
            mv.setViewName("partner/list");
            return mv;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "toAddIntent/{id}", method = RequestMethod.GET)
    public ModelAndView addIntent(@PathVariable("id") Long categoryId, HttpSession session) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("intentAdd")) {
            ModelAndView mv = new ModelAndView();
            mv.addObject("categoryId", categoryId);
            mv.setViewName("partner/addIntent");
            return mv;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "toAdd/{categoryAlias}", method = RequestMethod.GET)
    public ModelAndView add(@PathVariable("categoryAlias") String categoryAlias,
        HttpSession session) {

        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();
        if (currentUser.isPermitted("partner")) {
            ModelAndView mv = new ModelAndView();
            Company company = companyService.findOne(principal.getCompanyId());
            mv.addObject("address", company.getCityName());
            if ("weihu".equals(categoryAlias)) {
                List<Intent> list = intentService.findByCategoryAlias(categoryAlias);
                mv.addObject("intents", list);
            }
            mv.addObject("categoryAlias", categoryAlias);
            mv.setViewName("partner/add");
            return mv;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "createIntent", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> createIntent(
        @RequestParam("categoryAlias") String categoryAlias,
        @RequestParam("name") String name,
        @RequestParam("alias") String alias) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("intentAdd")) {
            Map<String, Object> result = new HashMap<String, Object>();
            Intent intent = new Intent();
            intent.setAlias(alias);
            intent.setName(name);
            intent.setCategoryAlias(categoryAlias);
            Intent save = intentService.save(intent);
            if (save != null) {
                result.put("success", true);
                result.put("message", "保存成功!");
            } else {
                result.put("success", false);
                result.put("message", "保存失败!");
            }
            return result;
        } else {
            throw new NoPermissionException();
        }
    }

    /**
     * 保存合作商家
     *
     * @param categoryId 主分类Id
     * @param intentId   子分类Id
     * @param name       商家名称
     * @param phone      商家电话
     * @param address    商家地址
     * @param city       城市
     * @param province   省份
     * @param county     区县
     * @param intro      详情介绍
     * @param lat
     * @param lng
     * @return
     */
    @RequestMapping(value = "create", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> create(
        @RequestParam("name") String name,
        @RequestParam("phone") String phone,
        @RequestParam("categoryAlias") String categoryAlias,
        @RequestParam(required = false, value = "intentId") Long intentId,
        @RequestParam("address") String address,
        @RequestParam("city") String city,
        @RequestParam("province") String province,
        @RequestParam("county") String county,
        @RequestParam("lat") Double lat,
        @RequestParam("lng") Double lng,
        @RequestParam("intro") String intro,
        @RequestParam(required = false, value = "img1") String img1,
        @RequestParam(required = false, value = "img2") String img2,
        @RequestParam(required = false, value = "img3") String img3,
        @RequestParam(required = false, value = "img4") String img4) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("partner")) {
            Map<String, Object> result = new HashMap<String, Object>();
            Partner partner = new Partner();
            partner.setIntentId(intentId);
            partner.setCategoryAlias(categoryAlias);
            partner.setName(name);
            partner.setPhone(phone);
            partner.setAddress(address);
            partner.setCity(city);
            partner.setProvince(province);
            partner.setCounty(county);
            partner.setIntro(intro);
            partner.setLat(lat);
            partner.setLng(lng);
            List<String> imgs = new ArrayList<String>();
            if (StringUtils.isNotBlank(img1)) {
                imgs.add(img1);
            }
            if (StringUtils.isNotBlank(img2)) {
                imgs.add(img2);
            }
            if (StringUtils.isNotBlank(img3)) {
                imgs.add(img3);
            }
            if (StringUtils.isNotBlank(img4)) {
                imgs.add(img4);
            }
            Partner save = partnerService.save(partner, imgs);

            if (save != null) {
                result.put("success", true);
                result.put("message", "保存成功!");
            } else {
                result.put("success", false);
                result.put("message", "保存失败!");
            }
            return result;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "detail/{id}", method = RequestMethod.GET)
    public ModelAndView detail(@PathVariable("id") Long id) {
        ModelAndView mv = new ModelAndView();
        Partner partner = partnerService.findById(id);
        if (partner != null) {
            mv.addObject("address", partner.getCity());
            String categoryAlias = partner.getCategoryAlias();
            List<PartnerImg> list = partner.getList();
            if (list.size() != 0) {
                for (int i = 0; i < list.size(); i++) {
                    PartnerImg img = list.get(i);
                    mv.addObject("img" + (i + 1), img.getImg());
                }
            }

            mv.addObject("categoryAlias", categoryAlias);
            mv.addObject("partner", partner);
            mv.setViewName("partner/detail");
        } else {
            mv.setViewName("partner/list");
        }
        return mv;
    }

    @RequestMapping(value = "edit/{id}", method = RequestMethod.GET)
    public ModelAndView toEdit(@PathVariable("id") Long id) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("partnerUpdate")) {
            ModelAndView mv = new ModelAndView();
            Partner partner = partnerService.findById(id);
            if (partner != null) {
                mv.addObject("address", partner.getCity());
                String categoryAlias = partner.getCategoryAlias();
                if ("weihu".equals(categoryAlias)) {
                    List<Intent> list = intentService.findByCategoryAlias(categoryAlias);
                    mv.addObject("intents", list);
                }
                List<PartnerImg> list = partner.getList();
                if (list.size() != 0) {
                    for (int i = 0; i < list.size(); i++) {
                        PartnerImg img = list.get(i);
                        mv.addObject("img" + (i + 1), img.getImg());
                    }
                }

                mv.addObject("categoryAlias", categoryAlias);
                mv.addObject("partner", partner);
                mv.setViewName("partner/edit");
            } else {
                mv.setViewName("partner/list");
            }
            return mv;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "updateIntent", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> updateIntent(
        @RequestParam("id") Long id,
        @RequestParam("name") String name) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("intentUpdate")) {
            Map<String, Object> result = new HashMap<String, Object>();
            Intent intent = intentService.findById(id);
            intent.setName(name);
            intent = intentService.updateIntent(intent);
            if (intent != null) {
                result.put("success", true);
                result.put("message", "修改成功!");
            } else {
                result.put("success", false);
                result.put("message", "修改失败!");
            }
            return result;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "update", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> update(
        @RequestParam("id") Long id,
        @RequestParam("name") String name,
        @RequestParam("phone") String phone,
        @RequestParam("categoryAlias") String categoryAlias,
        @RequestParam(required = false, value = "intentId") Long intentId,
        @RequestParam("address") String address,
        @RequestParam("city") String city,
        @RequestParam("province") String province,
        @RequestParam("county") String county,
        @RequestParam("lat") Double lat,
        @RequestParam("lng") Double lng,
        @RequestParam("intro") String intro,
        @RequestParam(required = false, value = "img1") String img1,
        @RequestParam(required = false, value = "img2") String img2,
        @RequestParam(required = false, value = "img3") String img3,
        @RequestParam(required = false, value = "img4") String img4) {
        Subject subject = SecurityUtils.getSubject();
        Map<String, Object> result = new HashMap<String, Object>();
        if (subject.isPermitted("partnerUpdate")) {
            Partner partner = partnerService.findById(id);
            if (intentId != null && intentId != 0) {
                partner.setIntentId(intentId);
            }
            partner.setCategoryAlias(categoryAlias);
            partner.setName(name);
            partner.setPhone(phone);
            partner.setAddress(address);
            partner.setCity(city);
            partner.setProvince(province);
            partner.setCounty(county);
            partner.setIntro(intro);
            partner.setLat(lat);
            partner.setLng(lng);
            List<String> imgs = new ArrayList<String>();
            if (StringUtils.isNotBlank(img1)) {
                imgs.add(img1);
            }
            if (StringUtils.isNotBlank(img2)) {
                imgs.add(img2);
            }
            if (StringUtils.isNotBlank(img3)) {
                imgs.add(img3);
            }
            if (StringUtils.isNotBlank(img4)) {
                imgs.add(img4);
            }
            Partner update = partnerService.update(partner, imgs);
            if (update != null) {
                result.put("success", true);
                result.put("message", "修改成功!");
            } else {
                result.put("success", false);
                result.put("message", "修改失败!");
            }
            return result;

        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "delete", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> delete(Long id) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("partnerDelete")) {
            Map<String, Object> result = new HashMap<String, Object>();
            String delete = partnerService.delete(id);
            if (StringUtils.isBlank(delete)) {
                result.put("success", true);
                return result;
            } else {
                result.put("success", false);
                result.put("message", "失败");
                return result;
            }
        } else {
            throw new NoPermissionException();
        }
    }


    @RequestMapping(value = "deleteIntent", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> deleteIntent(Long id) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("intentDelete")) {
            Map<String, Object> result = new HashMap<String, Object>();
            Intent intent = intentService.findById(id);
            if (intent != null) {
                String delete = partnerService.deleteIntent(intent.getId());
                if (StringUtils.isBlank(delete)) {
                    result.put("success", true);
                    return result;
                } else {
                    result.put("success", false);
                    result.put("message", "失败");
                    return result;
                }
            } else {
                result.put("success", false);
                result.put("message", "子类不存在");
                return result;
            }
        } else {
            throw new NoPermissionException();
        }
    }
}
